import router from './index'
import homeRouter from './modules/home'
import errorRouter from './modules/error'
import remainingRoutes from './modules/remaining'
import routesRoutes from './modules/routes'
import { getToken } from '@/utils/auth'
import { getUser, useUserStore } from '@/stores/user'

// 获取初始化的路由信息，未登录时的
export function initConstantRoutes() {
  const initRoutes = [...remainingRoutes, errorRouter]
  const token = getToken()
  if (token.accessToken) {
    const user = getUser()
    const { menus } = user
    const myRouters = filterRoutesByUserMenus(routesRoutes, menus)
    initRoutes.push(homeRouter)
    if (myRouters && myRouters.length > 0) {
      initRoutes.push(...(myRouters as any))
    }
  }
  return initRoutes
}

// 登陆后添加动态路由
export function addDynamicRoutes() {
  const userStore = useUserStore()
  if (userStore.menus) {
    if (!router.hasRoute('Welcome')) {
      const menus = userStore.menus
      const myRouters = filterRoutesByUserMenus(routesRoutes, menus)
      router.addRoute(homeRouter)
      if (myRouters && myRouters.length > 0) {
        myRouters.forEach((r) => {
          router.addRoute(r as any)
        })
      }
    }
  }
}

// 登出后重置动态路由
export function resetDynamicRoutes() {
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name !== 'Login' && name !== 'Error' && name !== 'Redirect') {
      router.removeRoute(route.name as string)
    }
  })
}

// 通过用户菜单权限过滤菜单
export function filterRoutesByUserMenus(routes: RouteConfigsTable[], menus: string[]) {
  if (menus && menus.length > 0) {
    // 数组深拷贝
    const routesCopy = deepCopyRoutes(routes)
    return routesCopy.filter((route) => {
      if (route.children) {
        route.children = filterRoutesByUserMenus(route.children, menus)
      }
      if (route.children && route.children.length === 0) {
        return false
      }
      if (route.children && route.children.length > 0 && !route.redirect) {
        route.redirect = route.children[0].path
      }
      if (route.meta && route.meta.requiresAuth) {
        return menus.includes(route.name)
      } else {
        return true
      }
    })
  } else {
    return []
  }
}

function deepCopyRoutes(routes: RouteConfigsTable[]): RouteConfigsTable[] {
  return routes.map((route) => {
    const copiedRoute: RouteConfigsTable = {
      ...route,
      component: route.component
    }
    if (route.children) {
      copiedRoute.children = deepCopyRoutes(route.children)
    }
    return copiedRoute
  })
}
